package com.blandware.atleap.webapp.action.core.menuItem;

import com.blandware.atleap.common.Constants;
import com.blandware.atleap.model.core.ActionPage;
import com.blandware.atleap.model.core.ContentPage;
import com.blandware.atleap.model.core.Layout;
import com.blandware.atleap.model.core.Localizable;
import com.blandware.atleap.model.core.MenuItem;
import com.blandware.atleap.service.core.LookupManager;
import com.blandware.atleap.service.core.MenuManager;
import com.blandware.atleap.webapp.util.core.MenuUtil;
import com.blandware.atleap.webapp.util.core.WebappConstants;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.validator.GenericValidator;
import org.apache.struts.tiles.ComponentContext;
import org.apache.struts.tiles.ControllerSupport;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;


/**
 * <p>ListMenuItemsController class.  This class is used to display list of menu items from persistence layer
 * </p>
 * <p><a href="ListMenuItemsController.java.html"><i>View Source</i></a></p>
 *
 * @author Sergey Zubtsovskiy <a href="mailto:sergey.zubtsovskiy@blandware.com">&lt;sergey.zubtsovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.14 $ $Date: 2006/08/03 10:07:59 $
 */
public final class ListMenuItemsController extends ControllerSupport {

	protected transient final Log log = LogFactory.getLog(ListMenuItemsController.class);

	//~ Methods ================================================================
	/**
	 * Retrieves all menu items and puts them into request
	 *
	 * @param tilesContext   Current tile context
	 * @param request        Current request
	 * @param response       Current response
	 * @param servletContext Current Servlet Context
	 */
	public void execute(ComponentContext tilesContext,
	                    HttpServletRequest request,
	                    HttpServletResponse response,
	                    ServletContext servletContext) throws Exception {

		Long ownerId = (Long) request.getAttribute("ownerId");

		// get parent item ID from the session
		Long parentItemId = (Long) request.getSession().getAttribute(WebappConstants.MENU_ITEM_PARENT_ID_KEY);
		List menuItemsList = new ArrayList();

		ApplicationContext applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);

		if ( ownerId != null ) {
			LookupManager lookupManager = (LookupManager) applicationContext.getBean(Constants.LOOKUP_MANAGER_BEAN);
			Localizable owner = lookupManager.retrieveLocalizable(ownerId);

			String pageUri = null;
			String layoutDefinition = null;
			if ( owner instanceof Layout ) {
				Layout layout = (Layout) owner;
				layoutDefinition = layout.getDefinition();
			} else if ( owner instanceof ContentPage ) {
				ContentPage contentPage = (ContentPage) owner;
				pageUri = contentPage.getUri();
				layoutDefinition = contentPage.getLayout().getDefinition();
			} else if ( owner instanceof ActionPage ) {
				ActionPage actionPage = (ActionPage) owner;
				pageUri = actionPage.getUri();
				layoutDefinition = (String) request.getSession().getAttribute(WebappConstants.LAYOUT_DEFINITION_KEY);
			}

			// list of menu items will be shown if and only if layout definition is specified
			// otherwise, nothing will be displayed
			if ( !GenericValidator.isBlankOrNull(layoutDefinition) ) {
				// check parent's existence, because it might be deleted by another transaction
				if ( parentItemId != null ) {
					MenuManager menuManager = (MenuManager) applicationContext.getBean(Constants.MENU_MANAGER_BEAN);
					MenuItem parentItem = menuManager.retrieveMenuItem(parentItemId);
					if ( parentItem == null ) {
						// item does not exist
						parentItemId = null;
						request.getSession().removeAttribute(WebappConstants.MENU_ITEM_PARENT_ID_KEY);
					} else {
						// parent item is not null, save list of parents
						LinkedList parents = new LinkedList();
						while ( parentItem != null ) {
							parents.addFirst(parentItem);
							parentItem = parentItem.getParentItem();
						}
						request.setAttribute(WebappConstants.MENU_ITEM_PARENTS_LIST_KEY, parents);
					}
				}
				menuItemsList = new MenuUtil(request).getMenuItems(parentItemId, layoutDefinition, pageUri, false);
			}
		}

		request.setAttribute("menuItemsList", menuItemsList);
	}
}
